import {AsyncStorage} from 'react-native'
import Request from "../utils/Request";
import RouterServer from "../utils/RouterServer";

const STORAGE_KEY = "STORAGE_KEY_post";
import T from "../utils/T";
import {AuthModel, GroupModel, PostModel} from "./model";
import {kAuthorization} from "../constant";

const {Actions} = require("react-native-router-flux");

const {Toast} = require('antd-mobile');
export default {
    namespace: 'post',
    state: {
        loading: false,
        list: {
            content: []
        },
        totalPages: 0,
        last: true,

        postType: 'post',
        dynamicItem: null,
    },
    reducers: {
        save(state, {payload}) {
            return {...state, ...payload}
        }
    },
    effects: {


        // 保存到本地
        * saveToStorage({payload}, {call}) {
            yield call(AsyncStorage.setItem, STORAGE_KEY, JSON.stringify(payload))
        },

        // 本地恢复
        * restoreFromStorage({}, {call, put}) {
            const data = yield call(AsyncStorage.getItem, STORAGE_KEY);
            yield put({
                type: 'save',
                payload: {...JSON.parse(data)}
            });
        },
        //获取帖子列表
        * fetchData({payload}, {call, put, select}) {
            const auth: AuthModel = yield select(state => state.auth);
            const post: PostModel = yield select(state => state.post);
            payload['Authorization'] = `${auth.token_type} ${auth.access_token}`;
            yield put({
                type: 'save',
                payload: {loading: true}
            });
            const result = yield call(Request.get, Request.getApi().postList, payload);
            yield put({
                type: 'save',
                payload: {loading: false}
            });
            if (result) {
                if (payload.loadmore) {
                    const content = post.list.content;
                    post.list = result;
                    post.list.content = content.concat(result.content);
                } else {
                    post.list = result;
                }
                yield put({
                    type: 'save',
                    payload: {...post}
                })
            }
        },
        //新建评论
        * newComment({payload}, {call, put, select}) {
            // console.log(`%c 将要发送:\n\t%c${payload.message}\n`, 'color:green', 'color:red');
            const auth: AuthModel = yield select(state => state.auth);
            const post: PostModel = yield select(state => state.post);
            const group: GroupModel = yield select(state => state.group);

            let params = {};
            params['Authorization'] = `${auth.token_type} ${auth.access_token}`;
            params['Content-Type'] = `application/json`;

            params['params'] = {content: payload.message, user: {id: auth.userInfo.id}};
            const data = yield call(Request.post, Request.getApi().newComment, params);
            if (data) {
                params['params'] = data;

                let url = Request.getApi().postComment + `/${payload.id}`;
                if (payload.postType === 'group') {
                    url = Request.getApi().groupPostComment + `/${payload.id}`;
                }
                const result: postItem = yield call(Request.put, url, params);
                if (result) {
                    result.comments[result.comments.length - 1].user = auth.userInfo;
                    if (payload.postType === 'group') {
                        const index = group.postList.indexOf(payload.item);
                        if (index !== -1) {
                            group.postList[index] = result;
                        }
                        post.dynamicItem = result;
                        yield put({type: 'group/save', payload: {...group}})
                        yield put({type: 'save', payload: {...post}})
                    } else {
                        const index = post.list.content.indexOf(payload.item);
                        if (index !== -1) {
                            post.list.content[index] = result;
                        }
                        post.dynamicItem = result;
                        yield put({type: 'save', payload: {...post}})
                    }
                }
            }
        },

        //获取评论列表
        * fetchCommentList({payload}, {call, put, select}) {

        },

        //跳转详情页
        * detail({payload}, {put, call}) {
            yield put({
                type: 'save',
                payload
            });
            yield call(RouterServer.push, 'postingsDetail')
        },
        //点赞
        * praise({payload}, {call, put, select}) {
            const auth: AuthModel = yield select(state => state.auth);
            const post: PostModel = yield select(state => state.post);
            const group: GroupModel = yield select(state => state.group);
            let params = {};
            params['Authorization'] = auth.token_type + ' ' + auth.access_token;
            params['Content-Type'] = `application/json`;
            params['params'] = {
                typeId: payload.typeId,
                userId: auth.userInfo.id,
                userName: auth.userInfo.nickName,
                companyName: auth.userInfo.company.name,
                avatar: auth.userInfo.avatar,
            };

            let type = payload.type;
            if (payload.type === 'post') {
                if (payload.from === 'group') {
                    type = 'group_post';
                }
            }
            const praise: praise = yield call(Request.post, Request.getApi().praise + `/${type}`, params);
            if (praise) {
                if (payload.type === 'post') {
                    if (post.dynamicItem) {
                        post.dynamicItem.praise = praise;
                    }
                    if (payload.from === 'group') {
                        const index = group.postList.indexOf(payload.item);
                        const index1 = auth.groupNews.indexOf(payload.item);
                        if (index !== -1) {
                            const postItem: postItem = payload.item;
                            postItem.praise = praise;
                            group.postList[index] = postItem;
                        }
                        if (index1 !== -1) {
                            auth.groupNews[index1].praise = praise;
                        }
                    } else {
                        const index = post.list.content.indexOf(payload.item);
                        if (index !== -1) {
                            const postItem: postItem = payload.item;
                            postItem.praise = praise;
                            post.list[index] = postItem;
                        }
                    }
                } else if (payload.type === 'postcomment') {
                    //点赞帖子的评论
                    const index = post.dynamicItem.comments.indexOf(payload.item);
                    if (index !== -1) {
                        const comment: commentItem = payload.item;
                        comment.praise = praise;
                        post.dynamicItem.comments[index] = comment;
                    }
                }
                yield put({
                    type: 'save',
                    payload: {...post}
                });
                yield put({
                    type: 'group/save',
                    payload: {...group}
                });
                yield put({
                    type: 'auth/save',
                    payload: {...auth}
                });
            }
        },

        //新帖子
        * newPost({payload}, {call, put, select}) {
            // Toast.loading(T('loading'));
            const auth: AuthModel = yield select(state => state.auth);
            yield put({type: 'save', payload: {loading: true}});
            let params = {};
            params['Authorization'] = `${auth.token_type} ${auth.access_token}`;
            params['Content-Type'] = `application/json`;
            const file = payload.image;
            let pic = null;
            if (file) {
                const res: uploadResponse = yield call(Request.post, Request.getApi().upload + `/${payload.type}`, {file});
                if (res) {
                    pic = Request.checkImageUrl(res.url);
                }
            }
            let p = {
                content: payload.content,
                user: {id: auth.userInfo.id},
                area: {id: auth.userInfo.company.area.id}
            };
            if (pic) p['pic'] = pic;
            params['params'] = p;

            let url = Request.getApi().newPost;
            if (payload.type === 'groups') {
                const g: groupItem = payload.item;
                url = Request.getApi().newGroupPost;
                params['params']['groupId'] = g.id;
            }
            const res1 = yield call(Request.post, url, params);
            yield put({type: 'save', payload: {loading: false}});
            if (res1) {
                yield call(RouterServer.pop)
            }
        },

        * deletePost({payload}, {call, put, select}) {
            const auth: AuthModel = yield select(state => state.auth);
            const post: PostModel = yield select(state => state.post);
            payload[kAuthorization] = auth.token_type + ' ' + auth.access_token;
            const res = yield call(Request.del, Request.getApi().newPost + `/${payload.post.id}`, payload);
            if (res) {
                yield put({
                    type: 'auth/fetchData',
                    payload: {
                        pi: 1,
                        ps: 5
                    }
                });
                console.log(Actions.currentScene);
                switch (Actions.currentScene) {
                    case '_community': {

                    }
                        break;
                    case 'postingsDetail': {
                        yield call(RouterServer.pop)
                    }
                        break;
                    default:
                        break;
                }

            }
        },


        //删除评论
        * deleteComment({payload}, {call, put, select}) {
            const auth: AuthModel = yield select(state => state.auth);
            const post: PostModel = yield select(state => state.post);
            let comment = payload.comment;
            delete payload.comment;
            payload[kAuthorization] = auth.token_type + ' ' + auth.access_token;

            console.log(payload);
            const res = yield call(Request.del, Request.getApi().deleteComment + `/${payload.type}`, payload);
            if (res) {
                const index = post.dynamicItem.comments.indexOf(comment);

                if (index !== -1) {
                    post.dynamicItem.comments.splice(index, 1);
                    yield put({
                        type: 'save',
                        payload: {
                            ...post
                        }
                    })
                }
            }
        },
    },
    subscriptions: {
        setup({dispatch}) {

        }
    },
};
